#!/bin/bash

set -eux # -x for verbose logging to juju debug-log

# TODO V Preserve the existing configuration, so that multiple LUNs can be created.

szDefaultReleaseType="production"

juju-log "=================================  CONFIG CHANGE ===================="
juju-log --log-level INFO "log-level=INFO changing config for iscsi."
juju-log --log-level INFO -l INFO "both at INFO changing config for iscsi."

juju-log --log-level DEBUG "DDD reading configuration variables."


################################
# CONFIG-CHANGED
################################


#if [ "$szReleaseType" == "test" ]
#then
#  juju-log "DDD creating a test file."
#  dd if=/dev/zero of=/storage/lun1.img bs=1024k count=2000
#  juju-log "DDD cp config_test_ietd_conf /etc/ietd.conf"
#  cp config_test_ietd_conf /etc/ietd.conf
#fi

# can be ADD | DEL
szCfgOperation=`config-get CfgOperation`

# can be FLAT | LVM | DEV
szLunType=`config-get LunType`

# In MB. 
szLunSize=`config-get LunSize`

szLunName=`config-get LunName`

# TODO put default values in all non essential variables.
# TODO stop if OP or NAME isn't given.
if [ "$szCfgOperation" != "NONE" ];
then
  if [ "$szCfgOperation" = "ADD" ];
  then
    nError=0
    juju-log "III CfgOperation = ADD"
    if [ "$szLunType" != "flat" ];
    then
      nError=1
      juju-log "EEE LunType not 'flat'"
    fi
    if [ -z "$szLunSize" ];
    then
      nError=1
      juju-log "EEE LunSize not given."
    fi
    if [ -z "$szLunName" ];
    then
      nError=1
      juju-log "EEE LunName not given."
    fi
    if [ $nError = 1 ];
    then
      exit 1
    fi
  else
    juju-log "EEE the only CfgOperation supported is 'ADD'.  '$szCfgOperation' not supported."
    exit 1
  fi
  szStorageName="/storage/${szLunName}.img"
  szStorageCreateCommand="dd if=/dev/zero of=$szStorageName bs=1024k count=$szLunSize"
  juju-log "III Generating the storage: $szStorageCreateCommand"
  `$szStorageCreateCommand`
  # TODO V check return value.

  # TODO N for more info see: man ietd.conf
  szDatePart=`date "+%Y-%m"`
  szIetdConfFileName="/etc/iet/ietd.conf"
  echo "# Updated by config-changed." >> $szIetdConfFileName
  szHostname=`hostname -f`
  # TODO V change the hostname into the reverse fqn.
  szTargetName="iqn.${szDatePart}.${szHostname}:storage.${szLunName}"
  echo "Target ${szTargetName}" >> $szIetdConfFileName
  echo "    # first lun, listed, must be '0' then increment after that." >> $szIetdConfFileName
  echo "    Lun 0 Path=${szStorageName},Type=fileio" >> $szIetdConfFileName
  echo "    Alias $szLunName" >> $szIetdConfFileName

  juju-log "DDD Maybe later I should echo: $szTargetName IP_ADDR >> /etc/initiators.allow"
  
else
  juju-log "III No cfg operations given."
fi

# TODO Update the /etc/ietd.conf
# TODO Update /etc/initiators.allow
juju-log "III iscsi config changed."
